<template>
	<custom-range-vue @update-between-time="handleBetweenTime" :showLeft="showLeft" :showBack="false"
		class="customRange"></custom-range-vue>
	<scroll-view class="scroll" scroll-y :style="{'height':scrollHeight,'top':scrollTop}" :show-scrollbar="false"
		:scroll-top="top" @scroll="scroll">
		<view class="f-s-28 bold-text p-t-16">
			<text class="title" style="font-weight: 600;">集团汇总</text>
		</view>
		<view class="total-box flex m-t-20 flex-row flex-jus-bet">
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">
					总消费
				</view>
				<view class="bold-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{ total }}
					<text class="unit">万</text>
				</view>
				<view class="flex">
					<text class="m-r-5 title" style="font-size: 24rpx;color: var(--grey-text);">同比</text>
					<view class="img-wrap flex">
						<uni-icons v-if="totalRate>=0" type="arrow-up" size="14" color="#ff4b4e"></uni-icons>
						<uni-icons v-else type="arrow-down" size="14" color="#5cc94f"></uni-icons>
					</view>
					<text :class="totalRate>=0?'red-text':'green-text'">{{ Math.abs(totalRate) }}%</text>
				</view>
			</view>
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">总营业</view>
				<view class="bold-text red-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{ factTotal }}
					<text class="unit">万</text>
				</view>
				<view class="flex">
					<text class="m-r-5" style="font-size: 24rpx;color: var(--grey-text);">同比</text>
					<view class="img-wrap flex">
						<uni-icons v-if="factRate>=0" type="arrow-up" size="14" color="#ff4b4e"></uni-icons>
						<uni-icons v-else type="arrow-down" size="14" color="#5cc94f"></uni-icons>
					</view>
					<text :class="factRate>=0?'red-text':'green-text'">{{ Math.abs(factRate) }}%</text>
				</view>
			</view>
			<view class="flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 20rpx 0;width: 32%;">
				<view class="title" style="color: var(--grey-text);">总收款</view>
				<view class="bold-text red-text m-t-20 m-b-20"
					style="font-size: 30rpx;color: var(--white-text);font-weight: 500;">
					{{ recTotal }}
					<text class="unit">万</text>
				</view>
				<view class="flex flex-nowrap">
					<view class="m-r-5" style="font-size: 24rpx;color: var(--grey-text);white-space: nowrap;">同比</view>
					<view class="img-wrap flex">
						<uni-icons v-if="recRate>=0" type="arrow-up" size="14" color="#ff4b4e"></uni-icons>
						<uni-icons v-else type="arrow-down" size="14" color="#5cc94f"></uni-icons>
					</view>
					<text :class="recRate>=0?'red-text':'green-text'">{{ Math.abs(recRate) }}%</text>
				</view>
			</view>
		</view>
		<view class="detail-box flex flex-jus-bet m-t-20">
			<view class="detail-item flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 10rpx 0;width: 32%;">
				<view class="flex flex-col flex-jus-cen bold-text" style="padding-bottom: 10rpx;">
					<text class="title" style="color: var(--grey-text);">营业</text>
					<view class="money">
						{{ factTotal }}
						<text class="unit">万</text>
					</view>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ factNow }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">现结
						<text class="gold-text">{{ factNowRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ factMem }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">会员
						<text class="gold-text">{{ factMemRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0 0 0;">
					<view class="money">
						{{ factGz }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">挂账
						<text class="gold-text">{{ factGzRate }}%
						</text>
					</text>
				</view>
			</view>
			<view class="detail-item flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 10rpx 0;width: 32%;">
				<view class="flex flex-col flex-jus-cen bold-text" style="padding-bottom: 10rpx;">
					<text class="title" style="color: var(--grey-text);">非营</text>
					<view class="money">
						{{ freeTotal }}
						<text class="unit">万</text>
					</view>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ freeGift }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">免单
						<text class="gold-text">{{ freeGiftRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ freeSign }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">签送
						<text class="gold-text">{{ freeSignRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding-top: 10rpx;">
					<view class="money">
						{{ freeOther }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">其他
						<text class="gold-text">{{ freeOtherRate }}%
						</text>
					</text>
				</view>
			</view>
			<view class="detail-item flex flex-col flex-jus-cen"
				style="background-color: var(--bg-center-color);border-radius: 10rpx;padding: 10rpx 0;width: 32%;">
				<view class="flex flex-col flex-jus-cen bold-text" style="padding-bottom: 10rpx;">
					<text class="title" style="color: var(--grey-text);">收款</text>
					<view class="money">
						{{ recTotal }}
						<text class="unit">万</text>
					</view>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ recCust }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">消费
						<text class="gold-text">{{ recCustRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding: 10rpx 0;">
					<view class="money">
						{{ recChar }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">充值
						<text class="gold-text">{{ recCharRate }}%
						</text>
					</text>
				</view>
				<view class="flex flex-col flex-jus-cen bor-top" style="padding-top: 10rpx;">
					<view class="money">
						{{ recOther }}
						<text class="unit">万</text>
					</view>
					<text class="title" style="color: var(--grey-text);font-size: 24rpx;">其他
						<text class="gold-text">{{ recOtherRate }}%
						</text>
					</text>
				</view>
			</view>
		</view>
		<view class="f-s-28 bold-text m-t-20 m-b-20">
			<text class="title" style="font-weight: 600;">集团走势(近七天)</text>
		</view>
		<view class="cavas" style="background-color: var(--bg-center-color);">
			<qiun-data-charts type="tarea" :opts="opts" :chartData="chartData" />
		</view>
		<view class="f-s-28 bold-text m-t-20 m-b-20">
			<text class="title" style="font-weight: 600;">分店营业</text>
		</view>
		<view v-for="(it, idx) in rank" :key="idx" class="rank-item flex"
			style="background: var(--bg-center-color);border-radius: 8rpx;padding: 0 20rpx;"
			:style="{'marginTop':idx!=0?'20rpx':'0'}">
			<view class="sort flex-shrink">
				<text style="font-size: 26rpx;color: var(--white-text);">{{ idx + 1 }}</text>
			</view>
			<view class="flex-1 flex flex-jus-bet p-l-20">
				<view>
					<text style="font-size: 26rpx;color: var(--white-text);">{{ it.name }}</text>
				</view>
				<view class="bold-text red-text">
					<text style="font-size: 28rpx;color: var(--white-text);font-weight: 500;">{{ it.total }}</text>
				</view>
			</view>
		</view>
		<bottom-company-vue :footerStyle="footerStyle"></bottom-company-vue>
	</scroll-view>
	<custom-loading-vue ref="loading"></custom-loading-vue>
	<wrap-version-update id="557211668471877" :lines="10" apiUrl="https://app.skunld.net/check/Request.php"
		@finish="updateFinish" @error="updateError" :auto="false" ref="versionRef"></wrap-version-update>
		<tab-bar-vue :act="0"></tab-bar-vue>
</template>

<script setup>
	import customRangeVue from '@/components/customRange.vue'
	import customLoadingVue from '@/components/customLoading.vue'
	import bottomCompanyVue from '@/components/bottomCompany.vue'
	import WrapVersionUpdate from "@/uni_modules/wrap-version-update/components/wrap-version-update/wrap-version-update.nvue"
	import tabBarVue from "@/components/tabBar.vue"
	import {
		onMounted,
		getCurrentInstance,
		ref,
		watch,
		nextTick
	} from 'vue'
	import {
		deepClone
	} from '@/utils/index.js'
	import {
		onLoad,
		onShow
	} from '@dcloudio/uni-app'
	import dayjs from 'dayjs'

	const loading = ref(Object)
	const instance = getCurrentInstance()
	const commonJs = instance?.proxy?.$commonJs
	const footerStyle = ref({
		padding: '40rpx 0'
	})
	const betweenTime = ref([])
	const scrollHeight = ref('0px')
	const scrollTop = ref('0px')
	const showLeft = ref(false)
	const chartData = ref({})
	const opts = ref({
		color: ["#e87d7d"],
		padding: [10, 20, 0, 0],
		enableScroll: false,
		legend: {
			show: false
		},
		toolTip: {
			showArrow: false
		},
		xAxis: {
			calibration: true,
			disableGrid: true,
			boundaryGap: "center",
			// format: "xAxisDemo2",
			itemCount: 7
		},
		yAxis: {
			showTitle: true,
			gridType: "dash",
			disableGrid: true,
			dashLength: 2,
			data: [{
				title: '营业额(万)',
				titleOffsetX: 10,
				titleFontSize: 12,
				min: 0,
				max: 80
			}]
		},
		extra: {
			area: {
				type: "curve",
				opacity: 1,
				addLine: true,
				width: 2,
				gradient: true,
				activeType: "none"
			}
		}
	})
	const total = ref('0.00')
	const totalRate = ref(0)
	const factTotal = ref('0.00')
	const factRate = ref(0)
	const factNow = ref('0.00')
	const factNowRate = ref('0')
	const factMem = ref('0.00')
	const factMemRate = ref('0')
	const factGz = ref('0.00')
	const factGzRate = ref('0')
	const recTotal = ref('0.00')
	const recRate = ref(0)
	const recCust = ref('0.00')
	const recCustRate = ref('0')
	const recChar = ref('0.00')
	const recCharRate = ref('0')
	const recOther = ref('0.00')
	const recOtherRate = ref('0')
	const freeTotal = ref('0.00')
	const freeGift = ref('0.00')
	const freeGiftRate = ref('0')
	const freeSign = ref('0.00')
	const freeSignRate = ref('0')
	const freeOther = ref('0.00')
	const freeOtherRate = ref('0')
	const rank = ref([])
	let requestShopId = 0
	let userInfo = {}
	const top = ref(0)
	const old = ref({
		scrollTop: 0
	})
	const versionRef = ref(Object)

	watch(betweenTime, (newValue, oldValue) => {
		if (JSON.stringify(newValue) !== JSON.stringify(oldValue)) {
			top.value = old.value.scrollTop
			nextTick(() => {
				top.value = 0
			})
			getDate()
		}
	}, {
		deep: true
	})
	onLoad(() => {
		// commonJs.setTablebarIcon()
		requestShopId = commonJs.getRequestShopId()
		userInfo = commonJs.getUserInfo()
		// uni.setTabBar({
		//  "midButton": {
		//  	"iconPath":"/static/image/black_logo.png",
		//  	"iconWidth": "60px",
		//  	"height": "65px"
		//  },
		// });
		// uni.setTabBarItem({
		// 	index:2,
		// 	iconfont: '/static/image/black_logo.png',
		// 	success:function(){
		// 		console.log(2)
		// 	},
		// 	fail(e) {
		// 		console.log(e)
		// 	}
		// })
		// if (!requestShopId) {
		// 	return commonJs.hrefBind()
		// } else if (!userInfo || Object.keys(userInfo).length <= 0 || userInfo == undefined) {
		// 	return commonJs.hrefLogin()
		// }
	})

	const checkVertion = () => {
		versionRef.value.check()
	}

	const scroll = (e) => {
		old.value.scrollTop = e.detail.scrollTop
	}

	const handleBetweenTime = (timeRange) => {
		betweenTime.value = timeRange
	}

	const updateFinish = (e) => {
		// commonJs.showMessage('已是最新版本~')
	}

	const updateError = (e) => {
		commonJs.showMessage('更新请求出错~')
	}


	/**
	 * 获取集团营业数据
	 */
	const getDate = () => {
		let params = {
			group_id: requestShopId,
			begin_date: betweenTime.value[0] + ' 12:00:00',
			end_date: betweenTime.value[1] + ' 12:00:00',
			staff_id: userInfo && userInfo.hasOwnProperty('staff_id') ? userInfo.staff_id : 0
		}
		commonJs.queryCache('/group/getGroupShopBusiness', params, {
			before() {
				loading.value.show('加载中...')
			},
			success(res) {
				try {
					let cust = 0,
						beforeCust = 0
					let fact = 0,
						beforeFact = 0
					let factNowTotal = 0,
						factMemTotal = 0,
						factGzTotal = 0
					let rec = 0,
						beforeRec = 0
					let recCustTotal = 0,
						recCharTotal = 0,
						recOtherTotal = 0
					let free = 0
					let freeGiftTotal = 0,
						freeSignTotal = 0,
						freeOtherTotal = 0
					res.data.forEach(it => {
						cust += +it.business_data.now.total_money
						beforeCust += +it.business_data.before.total_money
						fact += +it.business_data.now.fact_money.total_money
						factNowTotal += +it.business_data.now.fact_money.money_item.now_money
						factMemTotal += +it.business_data.now.fact_money.money_item.member_money
						factGzTotal += +it.business_data.now.fact_money.money_item.gz_money
						beforeFact += +it.business_data.before.fact_money.total_money
						rec += +it.business_data.now.receipts_money.total_money
						recCustTotal += +it.business_data.now.receipts_money.money_item.customer_money
						recCharTotal += +it.business_data.now.receipts_money.money_item.charge_money
						recOtherTotal += +it.business_data.now.receipts_money.money_item.other_money
						beforeRec += +it.business_data.before.receipts_money.total_money
						free += +it.business_data.now.free_money.total_money
						freeGiftTotal += +it.business_data.now.free_money.money_item.gift_money
						freeSignTotal += +it.business_data.now.free_money.money_item.sign_money
						freeOtherTotal += +it.business_data.now.free_money.money_item.other_money
						// beforeFree += +it.business_data.before.free_money.total_money
					})
					total.value = (cust / 10000).toFixed(2)
					totalRate.value = beforeCust > 0 ? ((cust * 100 - beforeCust * 100) / beforeCust).toFixed(
							2) : cust >
						0 ? 100 : '0'
					if (totalRate.value.length > 6) {
						totalRate.value = 999999
					}
					factTotal.value = (fact / 10000).toFixed(2)
					factRate.value = beforeFact > 0 ? ((fact * 100 - beforeFact * 100) / beforeFact).toFixed(
							2) : fact >
						0 ? 100 : '0'
					if (factRate.value.length > 6) {
						factRate.value = 999999
					}
					recTotal.value = (rec / 10000).toFixed(2)
					recRate.value = beforeRec > 0 ? ((rec * 100 - beforeRec * 100) / beforeRec).toFixed(2) :
						rec > 0 ?
						100 : '0'
					if (recRate.value.length > 6) {
						recRate.value = 999999
					}
					freeTotal.value = (free / 10000).toFixed(2)
					factNow.value = (factNowTotal / 10000).toFixed(2)
					factMem.value = (factMemTotal / 10000).toFixed(2)
					factGz.value = (factGzTotal / 10000).toFixed(2)
					factNowRate.value = fact > 0 ? (factNowTotal * 100 / fact).toFixed(2) : '0'
					factMemRate.value = fact > 0 ? (factMemTotal * 100 / fact).toFixed(2) : '0'
					factGzRate.value = fact > 0 ? (factGzTotal * 100 / fact).toFixed(2) : '0'
					recCust.value = (recCustTotal / 10000).toFixed(2)
					recChar.value = (recCharTotal / 10000).toFixed(2)
					recOther.value = (recOtherTotal / 10000).toFixed(2)
					recCustRate.value = rec > 0 ? (recCustTotal * 100 / rec).toFixed(2) : '0'
					recCharRate.value = rec > 0 ? (recCharTotal * 100 / rec).toFixed(2) : '0'
					recOtherRate.value = rec > 0 ? (recOtherTotal * 100 / rec).toFixed(2) : '0'
					freeGift.value = (freeGiftTotal / 10000).toFixed(2)
					freeSign.value = (freeSignTotal / 10000).toFixed(2)
					freeOther.value = (freeOtherTotal / 10000).toFixed(2)
					freeGiftRate.value = free > 0 ? (freeGiftTotal * 100 / free).toFixed(2) : '0'
					freeSignRate.value = free > 0 ? (freeSignTotal * 100 / free).toFixed(2) : '0'
					freeOtherRate.value = free > 0 ? (freeOtherTotal * 100 / free).toFixed(2) : '0'
					rank.value = getRank(res.data).map(v => ({
						name: v.shop_alias,
						total: (v.business_data.now.fact_money.total_money / 10000).toFixed(2) +
							'万'
					}))
				} catch (error) {
					commonJs.showMessage(error)
				}
			},
			fail(err) {
				loading.value.hide()
				commonJs.logger.debug(err, 'error')
			},
			complete() {
				loading.value.hide()
			}
		})
	}

	/**
	 * 分店排名
	 * @param list
	 * @return {*}
	 */
	const getRank = list => {
		if (list.length < 2) {
			return list
		} else {
			const p = list[0]
			const left = list.filter(v => +v.business_data.now.fact_money.total_money > +p.business_data.now.fact_money
				.total_money)
			const cen = list.filter(v => +v.business_data.now.fact_money.total_money === +p.business_data.now
				.fact_money.total_money)
			const right = list.filter(v => +v.business_data.now.fact_money.total_money < +p.business_data.now
				.fact_money.total_money)
			return getRank(left).concat(cen, getRank(right))
		}
	}

	/**
	 * 获取集团排行
	 */
	const getLine = () => {
		let params = {
			group_id: requestShopId,
			staff_id: userInfo && userInfo.hasOwnProperty('staff_id') ? userInfo.staff_id : 0
		}
		commonJs.queryCache('/group/getGroupShopBusinessByDate', params, {
			before() {

			},
			success(res) {
				try {
					const yMax = Math.max(...(res.data.map(v => v.business_money / 10000))) + 1
					opts.value.yAxis.data[0].max = Math.floor(yMax)
					// let arr = deepClone(res.data).reverse()
					let list = res.data.map(v => dayjs(v.date).format('D号'))
					let response = {
						categories: list,
						series: [{
							name: "营业额(万)",
							data: res.data.map(v => (v.business_money / 10000).toFixed(2))
						}]
					}
					chartData.value = JSON.parse(JSON.stringify(response))
				} catch (error) {
					commonJs.logger.debug(error, 'error')
				}
			},
			fail(err) {
				commonJs.logger.debug(err, 'error')
			}
		})
	}

	/**
	 * 元素高度计算
	 */
	onMounted(() => {
		getLine()
		const query = uni.createSelectorQuery().in(this);
		query.select(".customRange")
			.boundingClientRect((data) => {
				scrollTop.value = data.height + 'px'
				let topHeight = data.height + 'px'
				scrollHeight.value = `calc(100vh - ${topHeight} - 50px)`
			})
			.exec();
		checkVertion()
	})
</script>

<style lang="scss" scoped>
	.money {
		font-size: 28rpx;
		color: var(--white-text);
		padding-top: 10rpx;
		font-weight: 500;
	}

	.unit {
		font-size: 24rpx;
		color: var(--grey-text);
		font-weight: 100;
	}

	.scroll {
		position: absolute;
		padding: 4rpx 30rpx 4rpx 30rpx;
		box-sizing: border-box;
	}

	.title {
		font-weight: 500;
		font-size: 28rpx;
		color: var(--text-color);
	}

	.total-box>view {
		width: 33.33%;
	}

	.detail-box>view {
		width: 31%;
		border-radius: 10rpx;

		&>view {
			width: 100%;

			text:last-child {
				margin-top: 6rpx;
			}
		}
	}

	.cavas {
		width: 100%;
		height: 470rpx;
		border-radius: 10rpx;
		padding: 20rpx 0;
	}

	.rank-item {

		// height: 46rpx;
		&>view {
			height: 60rpx;
			line-height: 60rpx;
		}

		.sort {
			width: 16%;
		}
	}

	.red-text {
		color: #ff4b4e;
		font-size: 24rpx;
	}

	.green-text {
		color: #5cc94f;
		font-size: 24rpx;
	}

	.gold-text {
		color: darkgoldenrod;
		font-weight: 24rpx;
	}

	.img-wrap {
		width: 30rpx;

		image {
			width: 100%;
		}
	}
</style>